package com.cloud.dataway.config.datasource;

public class DbContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public enum DataSource {
        MASTER("dataSource_master"),
        SLAVE("dataSource_slave");
        private String text;
        private DataSource(String text) {
            this.text = text;
        }
        public String getText() {
            return this.text;
        }
        public static DataSource parse(Object o) {
            if (!(o instanceof String)) {
                return MASTER;
            }
            String textStr = (String) o;
            for (DataSource ds : values()) {
                if (ds.getText().equals(textStr)) {
                    return ds;
                }
            }
            throw new IllegalArgumentException("Invalid text [" + textStr + "]");
        }
    }

    public static void setDbType(String dbType) {
        contextHolder.set(dbType);
    }
    public static void setDbType(DataSource dataSource) {
        if (dataSource == null) {
            dataSource = DataSource.MASTER;
        }
        contextHolder.set(dataSource.getText());
    }
    public static String getDbType() {
        return contextHolder.get();
    }
    public static void clearDbType() {
        contextHolder.remove();
    }
}
